package br.ucb.ucblive.HIB;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import br.ucb.ucblive.beans.Aluno;
import br.ucb.ucblive.beans.Moderador;

public class AlunoHIB{

	public Aluno consultarByLogin(String login) {
		Session session = HibernateUtil.getSession();
		try {
			Aluno obj = (Aluno) session.createCriteria(Aluno.class).
						add(Restrictions.eq("this.usuario.login", login)).
						setMaxResults(1).
						uniqueResult();
			return obj;
		} finally {
			session.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Aluno> listar(){
		Session session = HibernateUtil.getSession();
		try{
			return session.createCriteria(Aluno.class).list();
		}finally{
			session.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Aluno> listarOrdemCrescente(){
		Session session = HibernateUtil.getSession();
		try{
			return session.createCriteria(Aluno.class).addOrder(Order.asc("this.nome")).list();
		}finally{
			session.close();
		}
	}
	
	public void salvar(Aluno aluno) {
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		session.saveOrUpdate(aluno);
		transaction.commit();
		session.close();
	}

	public void excluir(Aluno aluno) {
		Session session = HibernateUtil.getSession();
		Transaction transaction = session.beginTransaction();
		session.delete(aluno);
		transaction.commit();
		session.close();
		
	}
	
	public Aluno consultar(int idAluno) {
		Session session = HibernateUtil.getSession();
		try {
			Aluno obj = (Aluno) session.get(Aluno.class,idAluno);
			return obj;
		} finally {
			session.close();
		}
	}
	
	public Aluno consultarByMatricula(String matricula) {
		Session session = HibernateUtil.getSession();
		try {
			Aluno obj = (Aluno) session.createCriteria(Aluno.class).
						add(Restrictions.eq("this.matricula", matricula)).
						setMaxResults(1).
						uniqueResult();
			return obj;
		} finally {
			session.close();
		}
	}
}
